package com.example.blue;

import static com.example.blue.ProcessingFunction.Blank;

import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.chaquo.python.PyException;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class DataProcessorManager {

    public static int temp = 1;

    // 回调接口，用于向 UI 报告处理结果
    public interface DataUpdateListener {
        void onDataProcessed(ProcessedData data);
    }
    private static DataProcessorManager instance;
    private static final String TAG = "DataProcessorManager";
//    private final ConcurrentLinkedQueue<byte[]> dataQueue;
    private ExecutorService executor;
    private final CombinedDataProcessor processor;
    private ProcessingFunction currentFunction;
    private final Object stateLock = new Object();
    private long lastLogTimeMillis = 0;

    private StringBuffer sb = new StringBuffer();
    private StringBuffer rawsb = new StringBuffer();
    private StringBuffer testsb = new StringBuffer();
    private static String matfile = "modelPara.mat";

    private static String accbiasfile = "AccGyro1.txt";

    private static String magbiasfile = "mag1.txt";
    private static long prev = 0l;
    private static int count = 0;
    private static int startcount = 0;
    private static int testcount = 0;
    private static double[] qs2F = new double[4];
    // UI 线程的 Handler，用于将结果发送到 UI 线程
    private DataUpdateListener dataUpdateListener;
    private String deviceMac;
    private String handDir="L";
    private LinkedBlockingDeque<byte[]> dataQueue = new LinkedBlockingDeque<>();
    private final ExecutorService FILE_IO_POOL =
            Executors.newSingleThreadExecutor();
    private static final int COLLECTION_SIZE_DUIZHIBIAS = 101;
    private static final int COLLECTION_SIZE_DUIZHIOUT = 1001;
    private static final int COLLECTION_SIZE_ZHENCHAN = 1501;
    private static final int COLLECTION_SIZE_MAGBAIS = 2001;
    private static final int COLLECTION_SIZE_ACCBAIS=1001;
    private ProcessedData result = new ProcessedData("0");

    // CPU 核心数量
    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    private final Handler uiHandler = new Handler(Looper.getMainLooper());
    // CPU 密集线程数一般 = CPU_COUNT + 1
    private static final int CORE_POOL_SIZE = CPU_COUNT;

    public static final ExecutorService CPU_POOL =
            new ThreadPoolExecutor(
                    CORE_POOL_SIZE,
                    CORE_POOL_SIZE,
                    0L,
                    TimeUnit.MILLISECONDS,
                    new LinkedBlockingQueue<>(1000),        // 避免 OOM
                    new ThreadPoolExecutor.DiscardOldestPolicy()   // 最稳，不会卡死
            );
    public void setDeviceMac(String mac){
        deviceMac =mac;
    }
    public void setHandDir(String dir){
        handDir=dir;
    }
    private DataProcessorManager(LinkedBlockingDeque<byte[]> dataQueue) {
        this.dataQueue = dataQueue;
        this.executor = Executors.newSingleThreadExecutor();
        this.processor = new CombinedDataProcessor();
        this.currentFunction = Blank; // 默认功能
        qs2F[0] = 0.8243190069059947;
        qs2F[1] = -0.0805442381982586;
        qs2F[2] = -0.0923239194907208;
        qs2F[3] = 0.5527088695112896;
        File magbias = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOCUMENTS), deviceMac+"_magbias.txt");
        File accgyrobias = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOCUMENTS), deviceMac+"_accgyrobias.txt");
        if(magbias.exists()){
            if(utils.fileContainsNaN(magbias)==false) {
                magbiasfile = deviceMac + "_magbias.txt";
            }
        }
        if(accgyrobias.exists()){
            if(utils.fileContainsNaN(accgyrobias)==false) {
                accbiasfile = deviceMac + "_accgyrobias.txt";
            }
        }
    }
    public static DataProcessorManager getInstance(LinkedBlockingDeque<byte[]> dataQueue) {
        instance = new DataProcessorManager(dataQueue);
        return instance;
    }
    public void startProcessing() {
        if (executor.isShutdown() || executor.isTerminated()) {
            executor= Executors.newSingleThreadExecutor();
        }
        executor.execute(() -> {
            while (true) {
//                byte[] data = dataQueue.poll();
                byte[] data = null;
                if(dataQueue.size()!=0) {
                    try {
                        data = dataQueue.takeFirst();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        continue;    // 或者 break，根据你的逻辑
                    }
                }
                if (data != null) {
//                    ProcessedData result = new ProcessedData("0");
                    synchronized (stateLock) {
                        switch (currentFunction) {
                            //OK
                            case rawdata:
                                result = processor.rawData(data);
                                count++;
                                String rawStr = result.getValue();
                                if (count > 1000 && count < 2000) {
                                    rawsb.append(count + " " + rawStr + "\n");
                                }
                                if (count == 2000) {
                                    count = 0;
                                    currentFunction = Blank;
                                    String output2 = rawsb.toString();
                                    rawsb.setLength(0);
                                    try {
                                        utils.writeToFile(output2, deviceMac + "_rawdata.txt");
                                    } catch (IOException e) {
                                        throw new RuntimeException(e);
                                    }
                                }
                                break;
                            //OK
                            case rawout:
                                result = processor.rawout(data);
                                count++;
                                String rawoutStr = result.getValue();
                                if (count > startcount && count < startcount + 1001) {
                                    sb.append(count + " " + rawoutStr + "\n");
                                    rawsb.append(count + " " + utils.bytesToHex(data) + "\n");
                                }
                                if (count == startcount + 1001) {
                                    count = 0;
                                    currentFunction = Blank;
                                    String output1 = sb.toString();
                                    String output2 = rawsb.toString();
                                    sb.setLength(0);
                                    rawsb.setLength(0);
                                    try {
                                        utils.writeToFile(output1, deviceMac + "_rawout.txt");
                                        utils.writeToFile(output2, deviceMac + "_rawdata.txt");
                                    } catch (IOException e) {
                                        throw new RuntimeException(e);
                                    }
                                }
                                break;
                            //OK
                            case Blank:
                                count = 0;
                                testcount = 0;
                                sb.delete(0, sb.length());
                                rawsb.delete(0, rawsb.length());
                                result = processor.processFunction3(data);
                                break;

                            case Allout:

                                File magbias = new File(Environment.getExternalStoragePublicDirectory(
                                        Environment.DIRECTORY_DOCUMENTS), magbiasfile);
                                File accgyrobias = new File(Environment.getExternalStoragePublicDirectory(
                                        Environment.DIRECTORY_DOCUMENTS), accbiasfile);
                                System.out.println("DataProcessorManager-----Allout:"+accgyrobias.getAbsolutePath());

                                ProcessedData res;
                                if(magbias.exists() && accgyrobias.exists()) {
                                    try {
                                        res = processor.allout(data, accgyrobias.getAbsolutePath(), magbias.getAbsolutePath(), temp);
//                                    count = 0;
//                                    sb.delete(0, sb.length());
//                                    rawsb.delete(0, rawsb.length());

//                                    count++;
//                                    String AlloutStr = res.getValue();
//                                    if (count > startcount && count < startcount + 1001) {
//                                        sb.append(count + " " + AlloutStr + "\n");
//                                        rawsb.append(count + " " + utils.bytesToHex(data) + "\n");
//                                    }
//                                    if (count == startcount + 1001) {
//                                        count = 0;
//                                        currentFunction = Blank;
//                                        utils.writeToFile(sb.toString(), deviceMac+"_allout.txt");
//                                        utils.writeToFile(rawsb.toString(), deviceMac+"_allout_rawdata.txt");
//                                        sb.delete(0, sb.length());
//                                        rawsb.delete(0, rawsb.length());
//                                    }
                                    } catch (IOException e) {
                                        throw new RuntimeException(e);
                                    }
                                    result = res;
                                }else{
                                    result = new ProcessedData("success", "1", "fileNull");
                                }
                                break;
                            case MagBias:
                                result = processor.rawout(data);
                                String magoutStr = utils.bytesToHex(data);
                                testcount++;
                                testsb.append(count + " " + result.getValue() + "\n");
                                if(magoutStr.substring(30, 36).equals("000000")
//                                    || magoutStr.substring(30 + 36, 36 + 36).equals("000000")
//                                    || magoutStr.substring(30 + 36*2, 36 + 36*2).equals("000000")
//                                    || magoutStr.substring(30 + 36*3, 36 + 36*3).equals("000000")
//                                    || magoutStr.substring(30 + 36*4, 36 + 36*4).equals("000000")
//                                    || magoutStr.substring(30 + 36*5, 36 + 36*5).equals("000000")
                                )
                                {
                                    Log.d(TAG, "magoutStr: " + magoutStr.substring(30, 36));
                                    break;

                                }
                                count++;
                                if (count > startcount && count < startcount + COLLECTION_SIZE_MAGBAIS) {
                                    sb.append(count + " " + result.getValue() + "\n");
                                    rawsb.append(count + " " + utils.bytesToHex(data) + "\n");
                                }
                                if (count == startcount + COLLECTION_SIZE_MAGBAIS) {
                                    try {
                                        count = 0;
                                        testcount = 0;
                                        currentFunction = Blank;
                                        String output1 = sb.toString();
                                        String output2 = rawsb.toString();
                                        String output3 = testsb.toString();
                                        sb.setLength(0);
                                        rawsb.setLength(0);
                                        testsb.setLength(0);
                                        utils.writeToFile(output1, deviceMac + "_magbias_rawout.txt");
                                        utils.writeToFile(output2, deviceMac + "_magbias_rawdata.txt");
                                        utils.writeToFile(output3, deviceMac + "_magbias_test_rawdata.txt");
                                        File magRawoutfile = new File(Environment.getExternalStoragePublicDirectory(
                                                    Environment.DIRECTORY_DOCUMENTS), deviceMac + "_magbias_rawout.txt");
                                                        result = processor.magbias(magRawoutfile.getAbsolutePath());
                                                        if(result.getValue().contains("NaN")){
                                                            result = new ProcessedData("success", "1", "NaN");
                                                        }else {
                                                            utils.writeToFile(result.getValue(), deviceMac + "_magbias.txt");
                                                            magbiasfile = deviceMac + "_magbias.txt";
                                                        }

                                    } catch (IOException e) {
                                        throw new RuntimeException(e);
                                    }
                                }
                                break;
                            case Duizhiout:
                                count++;
                                File duizhimagbias = new File(Environment.getExternalStoragePublicDirectory(
                                        Environment.DIRECTORY_DOCUMENTS), magbiasfile);
                                File duizhiaccgyrobias = new File(Environment.getExternalStoragePublicDirectory(
                                        Environment.DIRECTORY_DOCUMENTS), accbiasfile);
                                System.out.println("DataProcessorManager-----accbiasfile:"+duizhiaccgyrobias.getAbsolutePath());

                                if(duizhimagbias.exists() && duizhiaccgyrobias.exists()) {
                                    try {
                                        result = processor.duizhiout(data, duizhiaccgyrobias.getAbsolutePath(), duizhimagbias.getAbsolutePath(), qs2F,temp);
                                        String duizhioutStr = result.getValue();
                                        if (count > startcount && count < startcount + COLLECTION_SIZE_DUIZHIOUT) {
                                            sb.append(count + " " + duizhioutStr + "\n");
                                            rawsb.append(count + " " + utils.bytesToHex(data) + "\n");
                                        }
                                        if (count == startcount + COLLECTION_SIZE_DUIZHIOUT) {
                                            count = 0;
                                            currentFunction = Blank;
                                            String output1 = sb.toString();
                                            String output2 = rawsb.toString();
                                            sb.setLength(0);
                                            rawsb.setLength(0);
                                        FILE_IO_POOL.execute(()->{
                                            try {
                                                utils.writeToFile(output1, deviceMac + "_" + temp + "_H.txt");
                                                utils.writeToFile(output2, deviceMac + "_duizhiout_rawdata.txt");
                                            } catch (IOException e) {
                                                throw new RuntimeException(e);
                                            }

                                            final File duizhioutfile = new File(Environment.getExternalStoragePublicDirectory(
                                                    Environment.DIRECTORY_DOCUMENTS), deviceMac + "_" + temp + "_H.txt");
                                            final File modelfile = new File(Environment.getExternalStoragePublicDirectory(
                                                    Environment.DIRECTORY_DOCUMENTS), matfile);
                                            if(utils.fileContainsNaN(duizhioutfile)){
                                                result = new ProcessedData("success", "1", "fileNull");
                                                dataQueue.clear();
                                                currentFunction = Blank;
                                            }else {
                                            CPU_POOL.execute(()->{
                                                ProcessedData computedResult = null; // 局部变量，存储计算结果
                                                try {
                                                    computedResult = processor.duizhi(duizhioutfile.getAbsolutePath(), modelfile.getAbsolutePath(), temp);
                                                    dataQueue.clear();

                                                } catch (Exception pyEx) {
                                                    Log.e("PythonError", "Python异常: " + pyEx.getMessage());
                                                    return;  // 不要再包 RuntimeException，防止崩 crash
                                                }

                                                // 2. 将最终结果作为 final 变量，用于 Handler 消息
                                                final ProcessedData finalResult = computedResult;

                                                // 3. 使用 Handler 将结果更新操作调度回主线程
                                                uiHandler.post(() -> {
                                                    // 在主线程上安全地更新实例变量 result
                                                    result = finalResult;

                                                    // 通知 UI 或外部监听器，结果已经准备好了
                                                    dataUpdateListener.onDataProcessed(result);

                                                });
                                            });
                                            }
                                        });

                                        }
                                    } catch (IOException e) {
                                        Log.e("IOException", "Exception: " + e.getMessage());
                                        return;
                                    } catch (Exception e) {
                                        Log.e("Exception", "Exception: " + e.getMessage());
                                        return;
                                    }
                                }else{
                                    result = new ProcessedData("success", "1", "fileNull");
                                    dataQueue.clear();
                                    currentFunction = Blank;
                                }
                                break;

//                            case DuizhiBias:
//                                count++;
//                                File filemagbias = new File(Environment.getExternalStoragePublicDirectory(
//                                        Environment.DIRECTORY_DOCUMENTS), deviceMac+"_magbias.txt");
//                                File fileaccgyrobias = new File(Environment.getExternalStoragePublicDirectory(
//                                        Environment.DIRECTORY_DOCUMENTS), deviceMac+"_accgyrobias.txt");
//                                if(filemagbias.exists()){
//                                    magbiasfile = deviceMac+"_magbias.txt";
//                                }
//                                if(fileaccgyrobias.exists()){
//                                    accbiasfile = deviceMac+"_accgyrobias.txt";
//                                }
//                                File dzmagbias = new File(Environment.getExternalStoragePublicDirectory(
//                                        Environment.DIRECTORY_DOCUMENTS), magbiasfile);
//                                File dzaccgyrobias = new File(Environment.getExternalStoragePublicDirectory(
//                                        Environment.DIRECTORY_DOCUMENTS), accbiasfile);
//                                String duizhioutStr = null;
//                                if(dzmagbias.exists() && dzaccgyrobias.exists()) {
//                                    try {
//                                        duizhioutStr = processor.allout(data, dzaccgyrobias.getAbsolutePath(), dzmagbias.getAbsolutePath(), temp).getValue();
//                                    } catch (IOException e) {
//                                        throw new RuntimeException(e);
//                                    }
//                                    if (count > startcount && count < startcount + 101) {
//                                        sb.append(count + " " + duizhioutStr + "\n");
//                                        rawsb.append(count + " " + utils.bytesToHex(data) + "\n");
//                                    }
//                                    if (count == startcount + 101) {
//                                        count = 0;
//                                        currentFunction = Blank;
//                                        String output1 = sb.toString();
//                                        String output2 = rawsb.toString();
//                                        sb.setLength(0);
//                                        rawsb.setLength(0);
//                                        FILE_IO_POOL.execute(()-> {
//                                                    utils.writeToFile(output1, deviceMac + "_duizhibias_rawout.txt");
//                                                    utils.writeToFile(output2, deviceMac + "_duizhibias_rawdata.txt");
//                                        });
//                                        File duizhibiasfile = new File(Environment.getExternalStoragePublicDirectory(
//                                                Environment.DIRECTORY_DOCUMENTS), deviceMac + "_duizhibias_rawout.txt");
//
//                                        try {
//                                            qs2F = processor.duizhibias(duizhibiasfile.getAbsolutePath());
//                                        } catch (Exception e) {
//                                            e.printStackTrace();
//                                        }
//
//                                        result = new ProcessedData("对指姿势校验完成", "duizhibias");
//                                    }
//                                }else{
//                                    result = new ProcessedData("success", "1", "fileNull");
//                                    currentFunction = Blank;
//                                }
//                                break;

                            case DuizhiBias:
                                count++;
                                File filemagbias = new File(Environment.getExternalStoragePublicDirectory(
                                        Environment.DIRECTORY_DOCUMENTS), deviceMac+"_magbias.txt");
                                File fileaccgyrobias = new File(Environment.getExternalStoragePublicDirectory(
                                        Environment.DIRECTORY_DOCUMENTS), deviceMac+"_accgyrobias.txt");
                                if(filemagbias.exists()){
                                    if(utils.fileContainsNaN(filemagbias)==false) {
                                        magbiasfile = deviceMac + "_magbias.txt";
                                    }else{
                                        magbiasfile = "mag1.txt";
                                    }
                                }else{
                                    magbiasfile = "mag1.txt";
                                }
                                if(fileaccgyrobias.exists()){
                                    if(utils.fileContainsNaN(fileaccgyrobias)==false) {
                                        accbiasfile = deviceMac + "_accgyrobias.txt";
                                    }else{
                                        accbiasfile = "AccGyro1.txt";
                                    }
                                }else{
                                    accbiasfile = "AccGyro1.txt";
                                }
                                System.out.println("DataProcessorManager-----magbiasfile:"+magbiasfile);

                                File dzmagbias = new File(Environment.getExternalStoragePublicDirectory(
                                        Environment.DIRECTORY_DOCUMENTS), magbiasfile);
                                File dzaccgyrobias = new File(Environment.getExternalStoragePublicDirectory(
                                        Environment.DIRECTORY_DOCUMENTS), accbiasfile);

                                String duizhioutStr = null;
                                if (dzmagbias.exists() && dzaccgyrobias.exists()) {
                                    try {
                                        // 2. 数据处理 (在当前单线程处理线程中)
                                        duizhioutStr = processor.allout(data, dzaccgyrobias.getAbsolutePath(), dzmagbias.getAbsolutePath(), temp).getValue();

                                        // 3. 收集数据
                                        if (count > startcount && count < startcount + COLLECTION_SIZE_DUIZHIBIAS) {
                                            sb.append(count).append(" ").append(duizhioutStr).append("\n");
                                            rawsb.append(count).append(" ").append(utils.bytesToHex(data)).append("\n");
                                        }

                                        // 4. 收集完成，启动后台 I/O 和计算
                                        if (count == startcount + COLLECTION_SIZE_DUIZHIBIAS) {
                                            // 冻结当前数据并重置状态 (在同步块内完成)
                                            final String output1 = sb.toString();
                                            final String output2 = rawsb.toString();
                                            sb.setLength(0);
                                            rawsb.setLength(0);
                                            currentFunction = Blank;
                                            count = 0;

                                            // 异步 I/O (写入文件)
                                            FILE_IO_POOL.execute(() -> {
                                                // 使用局部变量存储文件名
                                                final String rawOutFileName = deviceMac + "_duizhibias_rawout.txt";
                                                final String rawDataFileName = deviceMac + "_duizhibias_rawdata.txt";
                                                try {
                                                    utils.writeToFile(output1, rawOutFileName);
                                                    utils.writeToFile(output2, rawDataFileName);
                                                } catch (IOException e) {
                                                    throw new RuntimeException(e);
                                                }

                                                File duizhibiasfile = new File(Environment.getExternalStoragePublicDirectory(
                                                Environment.DIRECTORY_DOCUMENTS), rawOutFileName);
                                                // 异步 CPU 计算 (依赖写入的文件)
                                                CPU_POOL.execute(() -> {
                                                    try {
                                                        qs2F = processor.duizhibias(duizhibiasfile.getAbsolutePath());
                                                        // 成功后报告 UI 线程
                                                        uiHandler.post(() -> {
                                                            dataUpdateListener.onDataProcessed(new ProcessedData("对指姿势校验完成", "duizhibias"));
                                                        });
                                                    } catch (Exception e) {
                                                        Log.e(TAG, "Duizhibias calculation failed.", e);
                                                        // 失败后报告 UI 线程
//
                                                    }
                                                });
                                            });
                                            // 在数据处理线程中设置一个临时成功状态，等待后台任务完成
                                            result = new ProcessedData("对指姿势校验完成", "duizhibias");
                                        }

                                    } catch (IOException e) {
                                        // 5. 错误处理：捕获 IO 异常，记录并重置状态
                                        Log.e(TAG, "Error in DuizhiBias processing.", e);
                                        currentFunction = Blank;
                                        count = 0;
                                        dataQueue.clear();
                                        result = new ProcessedData("Error", e.getMessage(), "IO_EXCEPTION");
                                    }
                                } else {
                                    // 缺少依赖文件
                                    currentFunction = Blank;
                                    dataQueue.clear();
                                    result = new ProcessedData("success", "1", "fileNull");

                                }
                                break;
                            case AccGyroBias:
                                count++;
                                result = processor.rawout(data);
                                String accoutStr = processor.rawout(data).getValue();
                                if (count > startcount && count < startcount + COLLECTION_SIZE_ACCBAIS) {
                                    sb.append(count + " " + accoutStr + "\n");
                                    rawsb.append(count + " " + utils.bytesToHex(data) + "\n");
                                }
                                if (count == startcount + COLLECTION_SIZE_ACCBAIS) {
                                    try {
                                        count = 0;
                                        currentFunction = Blank;
                                        String output1 = sb.toString();
                                        String output2 = rawsb.toString();
                                        sb.setLength(0);
                                        rawsb.setLength(0);
                                        utils.writeToFile(output1, deviceMac + "_accgyrobias_rawout.txt");
                                        utils.writeToFile(output2, deviceMac + "_accgyrobias_rawdata.txt");

                                        File accRawoutfile = new File(Environment.getExternalStoragePublicDirectory(
                                                Environment.DIRECTORY_DOCUMENTS), deviceMac+"_accgyrobias_rawout.txt");
                                        result = processor.accgyrobias(accRawoutfile.getAbsolutePath());
                                        utils.writeToFile(result.getValue(), deviceMac+"_accgyrobias.txt");
                                        accbiasfile = deviceMac+"_accgyrobias.txt";
                                    } catch (IOException e) {
                                        throw new RuntimeException(e);
                                    }
                                }
                                break;
                            case FinalRes:
                                File p = new File(Environment.getExternalStoragePublicDirectory(
                                        Environment.DIRECTORY_DOCUMENTS), deviceMac+"_P_rawout.txt");
                                File rt = new File(Environment.getExternalStoragePublicDirectory(
                                        Environment.DIRECTORY_DOCUMENTS), deviceMac+"_RT_rawout.txt");
                                File pt = new File(Environment.getExternalStoragePublicDirectory(
                                        Environment.DIRECTORY_DOCUMENTS), deviceMac+"_PT_rawout.txt");
                                File ptt = new File(Environment.getExternalStoragePublicDirectory(
                                        Environment.DIRECTORY_DOCUMENTS), deviceMac+"_PTT_rawout.txt");
                                if(rt.exists() && p.exists() && pt.exists() && ptt.exists()) {
                                    if(utils.fileContainsNaN(p)==true){
                                        result = new ProcessedData("success", "1", "p_file_error");
                                        currentFunction = Blank;
                                    }else if(utils.fileContainsNaN(rt)==true){
                                        result = new ProcessedData("success", "1", "rt_file_error");
                                        currentFunction = Blank;
                                    }else if(utils.fileContainsNaN(pt)==true){
                                        result = new ProcessedData("success", "1", "pt_file_error");
                                        currentFunction = Blank;
                                    }else if(utils.fileContainsNaN(ptt)==true){
                                        result = new ProcessedData("success", "1", "ptt_file_error");
                                        currentFunction = Blank;
                                    }else {
                                        result = processor.zhenchan(rt.getAbsolutePath(), p.getAbsolutePath(), pt.getAbsolutePath(), ptt.getAbsolutePath());
                                        currentFunction = Blank;
                                    }
                                }else{
                                    result = new ProcessedData("success", "1", "fileNull");
                                    currentFunction = Blank;
                                }
                                break;
                            case PingJU:
                                count++;

                                File pjmagbias = new File(Environment.getExternalStoragePublicDirectory(
                                        Environment.DIRECTORY_DOCUMENTS), magbiasfile);
                                File pjaccgyrobias = new File(Environment.getExternalStoragePublicDirectory(
                                        Environment.DIRECTORY_DOCUMENTS), accbiasfile);
                                if(pjmagbias.exists() && pjaccgyrobias.exists()) {
                                    try {
                                        result = processor.allout(data, pjaccgyrobias.getAbsolutePath(), pjmagbias.getAbsolutePath(), temp);
                                        String pjoutStr = result.getValue();

                                        if (count > startcount && count < startcount + COLLECTION_SIZE_ZHENCHAN) {
                                            sb.append(count + " " + pjoutStr + "\n");
                                            rawsb.append(count + " " + utils.bytesToHex(data) + "\n");
                                        }
                                    } catch (IOException e) {
                                        throw new RuntimeException(e);
                                    }
                                    if (count == startcount + COLLECTION_SIZE_ZHENCHAN) {
                                        count = 0;
                                        currentFunction = Blank;
                                        String output1 = sb.toString();
                                        String output2 = rawsb.toString();
                                        sb.setLength(0);
                                        rawsb.setLength(0);
                                        FILE_IO_POOL.execute(()-> {
                                                    try {
                                                        utils.writeToFile(output1, deviceMac + "_P_rawout.txt");
                                                        utils.writeToFile(output2, deviceMac + "_pj_rawdata.txt");
                                                    } catch (IOException e) {
                                                        throw new RuntimeException(e);
                                                    }
                                                });
                                        result = new ProcessedData("平举文件储存完成", "success");
                                    }
                                }else{
                                    result = new ProcessedData("success", "1", "fileNull");
                                    currentFunction = Blank;
                                }
                                break;
                            case JingZhi:
                                count++;
                                File jzmagbias = new File(Environment.getExternalStoragePublicDirectory(
                                        Environment.DIRECTORY_DOCUMENTS), magbiasfile);
                                File jzaccgyrobias = new File(Environment.getExternalStoragePublicDirectory(
                                        Environment.DIRECTORY_DOCUMENTS), accbiasfile);
//                                if(count%100 == 0){
//
//                                    long time = System.currentTimeMillis()-prev;
//                                    System.out.println("test time: --------"+ time);
//                                    prev = System.currentTimeMillis();
//                                }
                                if(jzmagbias.exists() && jzaccgyrobias.exists()) {

                                    try {
                                        result = processor.allout(data, jzaccgyrobias.getAbsolutePath(), jzmagbias.getAbsolutePath(), temp);
                                    } catch (IOException e) {
                                        throw new RuntimeException(e);
                                    }

                                    String pjoutStr = result.getValue();
                                    String pjoutaccStr = result.getAcccle();
                                    if (count > startcount && count < startcount + COLLECTION_SIZE_ZHENCHAN) {
                                        sb.append(count + " " + pjoutStr + "\n");
                                        rawsb.append(count + " " + utils.bytesToHex(data) + "\n");
                                        testsb.append(count + " " + pjoutStr + " " + pjoutaccStr + "\n");
                                    }
                                    if (count == startcount + COLLECTION_SIZE_ZHENCHAN) {
                                        count = 0;
                                        currentFunction = Blank;
                                        String output1 = sb.toString();
                                        String output2 = rawsb.toString();
                                        String output3 = testsb.toString();
                                        sb.setLength(0);
                                        rawsb.setLength(0);
                                        testsb.setLength(0);
                                        FILE_IO_POOL.execute(()->{
                                            try {
                                                utils.writeToFile(output1, deviceMac + "_RT_rawout.txt");
                                                utils.writeToFile(output2, deviceMac + "_jz_rawdata.txt");
                                                utils.writeToFile(output3, deviceMac + "_jz_acc_outdata.txt");
                                            } catch (IOException e) {
                                                throw new RuntimeException(e);
                                            }

                                        });
                                        result = new ProcessedData("文件储存完成", "success");
                                    }
                                }else{
                                    result = new ProcessedData("success", "1", "fileNull");
                                    currentFunction = Blank;
                                }
                                break;
                            case WingBeating:
                                count++;
                                File wbmagbias = new File(Environment.getExternalStoragePublicDirectory(
                                        Environment.DIRECTORY_DOCUMENTS), magbiasfile);
                                File wbaccgyrobias = new File(Environment.getExternalStoragePublicDirectory(
                                        Environment.DIRECTORY_DOCUMENTS), accbiasfile);
                                if(wbmagbias.exists() && wbaccgyrobias.exists()) {
                                    try {
                                        result = processor.allout(data, wbaccgyrobias.getAbsolutePath(), wbmagbias.getAbsolutePath(), temp);
                                        String pjoutStr = result.getValue();

                                        if (count > startcount && count < startcount + COLLECTION_SIZE_ZHENCHAN) {
                                            sb.append(count + " " + pjoutStr + "\n");
                                            rawsb.append(count + " " + utils.bytesToHex(data) + "\n");
                                        }
                                    } catch (IOException e) {
                                        throw new RuntimeException(e);
                                    }
                                    if (count == startcount + COLLECTION_SIZE_ZHENCHAN) {
                                        count = 0;
                                        currentFunction = Blank;
                                        String output1 = sb.toString();
                                        String output2 = rawsb.toString();
                                        sb.setLength(0);
                                        rawsb.setLength(0);
                                        FILE_IO_POOL.execute(()-> {
                                                    try {
                                                        utils.writeToFile(output1, deviceMac + "_PT_rawout.txt");
                                                        utils.writeToFile(output2, deviceMac + "_wb_rawdata.txt");
                                                    } catch (IOException e) {
                                                        throw new RuntimeException(e);
                                                    }
                                                });
                                        result = new ProcessedData("文件储存完成", "success");
                                    }
                                }else{
                                    result = new ProcessedData("success", "1", "fileNull");
                                    currentFunction = Blank;
                                }
                                break;
                            case WingBeatingPlus:
                                count++;
                                File wbpmagbias = new File(Environment.getExternalStoragePublicDirectory(
                                        Environment.DIRECTORY_DOCUMENTS), magbiasfile);
                                File wbpaccgyrobias = new File(Environment.getExternalStoragePublicDirectory(
                                        Environment.DIRECTORY_DOCUMENTS), accbiasfile);
                                if(wbpmagbias.exists() && wbpaccgyrobias.exists()) {
                                    try {
                                        result = processor.allout(data, wbpaccgyrobias.getAbsolutePath(), wbpmagbias.getAbsolutePath(), temp);
                                        String pjoutStr = result.getValue();

                                        if (count > startcount && count < startcount + COLLECTION_SIZE_ZHENCHAN) {
                                            sb.append(count + " " + pjoutStr + "\n");
                                            rawsb.append(count + " " + utils.bytesToHex(data) + "\n");
                                        }
                                    } catch (IOException e) {
                                        throw new RuntimeException(e);
                                    }
                                    if (count == startcount + COLLECTION_SIZE_ZHENCHAN) {
                                        count = 0;
                                        currentFunction = Blank;
                                        String output1 = sb.toString();
                                        String output2 = rawsb.toString();
                                        sb.setLength(0);
                                        rawsb.setLength(0);
//                                        FILE_IO_POOL.execute(()-> {
                                                    try {
                                                        utils.writeToFile(output1, deviceMac + "_PTT_rawout.txt");
                                                        utils.writeToFile(output2, deviceMac + "_wbp_rawdata.txt");
                                                    } catch (IOException e) {
                                                        throw new RuntimeException(e);
                                                    }
//                                                });
                                        result = new ProcessedData("文件储存完成", "success");
                                    }
                                }else{
                                    result = new ProcessedData("success", "1", "fileNull");
                                    currentFunction = Blank;
                                }
                                break;
                            default:
                                result = new ProcessedData("0");
                                break;
                        }
                    }
                    final ProcessedData finalResult = result;
                    // 通过 UI Handler 将处理结果发送给监听器
                    if (dataUpdateListener != null) {
                        uiHandler.post(() -> dataUpdateListener.onDataProcessed(finalResult));
                    }

                    // 每隔 10 秒打印一次日志
//                    if (System.currentTimeMillis() - lastLogTimeMillis >= 10000) {
//                        Log.d(TAG, "Processor output: " + result.getValue());
//                        lastLogTimeMillis = System.currentTimeMillis();
//                    }
                }
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    return;
                }
            }
        });
    }
    public void setzero(){
        count = 0;
        testcount = 0;
        sb.delete(0, sb.length());
        rawsb.delete(0, rawsb.length());
    }

    public void stopProcessing() {
        executor.shutdownNow();
    }

    public void setProcessingFunction(ProcessingFunction function) {
        synchronized (stateLock) {
            this.currentFunction = function;
        }
    }

    // 设置回调监听器的方法
    public void setDataUpdateListener(DataUpdateListener listener) {
        this.dataUpdateListener = listener;
    }


}